<script setup>
import { onMounted, ref } from 'vue'
import { getData, searchData, getDataByCateId, successOrNot, del } from '@/api/check'
import useUserStore from '@/stores/modules/user'
import { getCategory } from '@/api/category'
import { getTableList } from '@/utils/Data'
import { ElMessage } from 'element-plus'
defineOptions({ name: 'BannerIndex' })
const userStore = useUserStore()
//定义数据存放数组
const tableData = ref(0)
//分页
const pag = ref({
  page: 1,
  pageSize: 10,
  pagetotal: 10
})
//定义类别筛选数组
const iniCategory = async () => {
  const { page, pageSize } = pag.value
  const res = await getCategory({ page, pageSize })
  CATEGORY.value = res.data.dataAll.map((item) => {
    return {
      text: item.category,
      value: item.id
    }
  })
  console.log(res)
}
iniCategory()
const CATEGORY = ref([])
//定义弹窗打开状态值
const isShow = ref(false)

//获取数据
const getList = () => {
  getTableList(getData, pag, tableData)
}
getList()
//清空弹窗内容
const clear = () => {
  isShow.value = false
  check.value = ref({ id: null, number: null, code: null, username: userStore.username })
  maxNumber.value = null
}
//数字范围
const maxNumber = ref(null)
//数字校验规则
const isNumber = (rule, value, callback) => {
  if (typeof value !== 'number' || isNaN(value)) {
    callback(new Error('请输入数字'))
  } else if (value < 1 || value > maxNumber.value) {
    console.log(11)
    callback(new Error(`数量范围为1-${maxNumber.value}`))
  } else {
    callback()
  }
}
//表单校验
const rule = ref({
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入数字', trigger: 'blur' },
    {
      validator: isNumber,
      trigger: 'blur'
    }
  ]
})

//复检数据
const check = ref({ id: null, quantity: null, code: null, username: userStore.username })
//复检状态
const checkStatus = ref([
  { value: 1, label: '检验通过' },
  { value: 0, label: '检验失败' }
])

//提交
const ruleForm = ref(null)
const submit = async () => {
  ruleForm.value.validate(async (ok) => {
    if (ok) {
      const res = await successOrNot(check.value)
      if (maxNumber.value === check.value.quantity) {
        //如果入库了全部的商品，则删除这条
        await del(check.value.id)
        ElMessage({
          type: 'success',
          message: '全部入库成功'
        })
      } else {
        ElMessage({
          type: 'success',
          message: '入库成功'
        })
      }
      clear()
      getList()
    } else {
      ElMessage({
        type: 'error',
        message: '请按要求填写'
      })
    }
  })
}

//分类筛选
const firstFilter = ref(true)
const categorySearch = async (value, column) => {
  if (firstFilter.value) {
    firstFilter.value = false
    if (value !== undefined) {
      if (column.property === 'category') {
        const res = await getDataByCateId(value)
        tableData.value = res.data
      }
    } else {
      getList()
    }
  }
}
const handleFilterChange = (filters) => {
  firstFilter.value = true
  if (filters.category) {
    categorySearch(filters.category[0], { property: 'category' }) // 传递正确的 column 参数
  }
}

//搜索逻辑
const searchDetail = ref(null)
const search = async (title) => {
  if (!searchDetail.value) {
    getList()
    return false
  }
  const res = await searchData(searchDetail.value)
  tableData.value = res.data
  searchDetail.value = null
}
</script>

<template>
  <div class="search">
    <el-input placeholder="搜索框" style="width: 240px" v-model="searchDetail"></el-input>
    <el-button @click="search">搜索</el-button>
  </div>
  <el-table style="width: 100%" :data="tableData" @filter-change="handleFilterChange">
    <el-table-column prop="id" label="ID" width="90" />
    <el-table-column prop="title" label="货品名" width="180" />
    <el-table-column prop="username" label="操作员名称" width="180" />
    <el-table-column prop="image" label="图片" width="180">
      <template #default="{ row }">
        <img :src="row.image" alt="" width="100px" />
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="数量" width="100" />
    <el-table-column
      prop="category"
      label="分类"
      width="90"
      column-key="category"
      :filters="CATEGORY"
      :filter-method="categorySearch"
      :filter-multiple="false"
    />
    <el-table-column prop="updateTime" label="添加时间" width="180" />
    <el-table-column prop="time" label="剩余待检天数" width="180">
      <template #default="{ row }">
        <div :class="row.time < 0 ? 'red' : 'green'">
          {{ row.time < 0 ? '逾期未检' : `剩余复检时间:${row.time}天` }}
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button
          size="small"
          type="success"
          @click="(isShow = true), (maxNumber = row.quantity), (check.id = row.id)"
          :disabled="row.quantity === 0"
        >
          复检
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="isShow" title="复检信息" :before-close="clear" width="20%">
    <el-form label-width="auto" :model="check" :rules="rule" ref="ruleForm">
      <el-form-item label="复检数量" prop="quantity">
        <el-input v-model.number="check.quantity"></el-input>
      </el-form-item>
      <el-form-item label="检验状态">
        <el-select v-model="check.code" placeholder="Select" size="large" style="width: 240px">
          <el-option
            v-for="item in checkStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-pagination
    background
    layout="prev, pager, next"
    :total="pag.pagetotal"
    v-model:page-size="pag.pageSize"
    v-model:current-page="pag.page"
    @change="getList"
  />
</template>
<style lang="scss" scoped>
.el-form-item {
  width: 240px;
}

.w600 {
  width: 600px;
}

.red {
  color: red;
}

.green {
  color: green;
}
</style>
